var express = require("express");
const Core = require("@alicloud/pop-core");
const authController = require("../controllers/authController");
const authMiddleware = require("../middleware/authMiddleware");
var router = express.Router();
var {
  UserModel,
  hospitalModel,
  DepartmentModel,
  RoleModel,
  PermissionModel,
  PositionModel,
} = require("../model/module/xsp_db");
/**
 * UserModel:用户表
 * hospitalModel:医院表
 * DepartmentModel:科室表
 * RoleModel:角色表
 * PositionModel:职位表
 * PermissionModel:权限表
 */
//token测试接口
router.get("/test", (req, res) => {
  res.send({ code: 200, msg: "token测试成功" });
})
// 登录用户---注册
router.post("/userAdd", async (req, res) => {
  let body = req.body;
  let result = await UserModel.find({ username: body.username });
  if (result.length > 0) {
    res.send({ code: 204, msg: "用户名已存在" });
  } else {
    UserModel.create(body);
    res.send({ code: 201, msg: "添加成功" });
  }
});
// 登录用户---登录
router.post("/login", authController.login);
// 刷新Token
router.post("/refresh-token", authController.refreshToken);

// 受保护的API接口使用authMiddleware进行身份验证
router.get("/protected", authMiddleware.authenticate, (req, res) => {
  res.json({ message: "Access granted", user: req.user });
});

//---------短信登录验证----------
// 生成随机验证码
function generateCode() {
  const characters =
    "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  let code = "";
  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    code += characters.charAt(randomIndex);
  }
  return code;
}
//获取验证码
router.post("/sendCode", (req, res) => {
  // const phoneNumber = req.body.phoneNumber; // 获取手机号码
  const code = generateCode(); // 生成验证码
  res.send({ code });
  // const params = {
  //     RegionId: "cn-hangzhou", // 短信服务所在区域，可以参考阿里云文档
  //     PhoneNumbers: phoneNumber, // 目标手机号码
  //     SignName: "奥特们", // 短信签名名称，需先在阿里云控制台中申请审核通过
  //     TemplateCode: "SMS_464500505", // 短信模板 CODE，需先在阿里云控制台中申请审核通过
  //     TemplateParam: JSON.stringify({
  //         // 短信模板参数，为 JSON 字符串格式
  //         code: code, // 模板中的变量名和对应的值
  //     }),
  // };
  // const requestOption = {
  //     // 设置请求超时时间等选项
  //     method: "POST",
  //     timeout: 5000,
  // };
  // const client = new Core({
  //     // 创建 Client 对象
  //     accessKeyId: "LTAI5tQV5cE5kmuDJzpj3SWU", // 替换成自己的 AccessKey ID
  //     accessKeySecret: "tgar5emNfQZcZavu0SfiTIjKb0eR5R", // 替换成自己的 AccessKey Secret
  //     endpoint: "https://dysmsapi.aliyuncs.com", // API 访问入口，根据实际情况修改
  //     apiVersion: "2017-05-25", // API 版本号，根据实际情况修改
  // });
  // // 调用 SendSms 方法发送短信
  // client.request("SendSms", params, requestOption).then(
  //     (result) => {
  //         console.log(result); // 打印发送结果
  //         res.status(200).json({
  //             // 返回状态码和生成的验证码
  //             message: "验证码已发送，请注意查收！",
  //             code: code,
  //         });
  //     },
  //     (ex) => {
  //         console.log(ex); // 打印异常信息
  //         res.status(500).json({
  //             // 返回错误状态码和错误信息
  //             message: "短信发送失败，请稍后重试！",
  //             code: 500
  //         });
  //     }
  // );
});
// 验证验证码的有效期
function isCodeValid(creationTime) {
  const currentTime = Date.now();
  const expirationTime = 5 * 60 * 1000; // 5分钟的毫秒数
  return currentTime - creationTime <= expirationTime;
}
// 登录用户---忘记密码
router.post("/forget", async (req, res) => {
  let { username, phone } = req.body;
  const inputCode = req.body.code; // 获取用户输入的验证码
  const generatedCode = req.body.generatedCode; // 获取之前生成的验证码
  const creationTime = req.body.creationTime._value; // 获取验证码生成时间
  let result = await UserModel.find({ username, phone });
  if (result.length > 0) {
    if (123 === 123 && isCodeValid(creationTime)) {
      // 验证码一致且在有效期内，登录成功
      await UserModel.updateOne(
        { username, phone },
        { password: req.body.password }
      );
      res.send({ code: 200, msg: "修改成功" });
    } else {
      // 验证码不一致或已过期，登录失败
      res.send({ code: 204, msg: "验证码错误或已过期，请重新获取！" });
    }
  } else {
    res.send({ code: 204, msg: "用户名或手机号错误" });
  }
});

//医院表添加
router.post("/hospitalAdd", async (req, res) => {
  let body = req.body;
  let result = await hospitalModel.find({ name: body.name });
  if (result.length > 0) {
    res.send({ code: 204, msg: "医院名已存在" });
  } else {
    hospitalModel.create(body);
    res.send({ code: 201, msg: "添加成功" });
  }
});

//科室表添加
router.post("/departmentAdd", async (req, res) => {
  let body = req.body;
  let result = await DepartmentModel.find({ hospital: body.hospital });
  if (result.length > 0) {
    if (result[0].hospital === body.hospital) {
      res.send({ code: 204, msg: "科室名已存在" });
    } else {
      DepartmentModel.create(body);
      res.send({ code: 201, msg: "添加成功" });
    }
  } else {
    DepartmentModel.create(body);
    res.send({ code: 201, msg: "添加成功" });
  }
});

//角色表添加
router.post("/roleAdd", async (req, res) => {
  let body = req.body;
  let result = await RoleModel.find({ department: body.department });
  if (result.length > 0) {
    if (result[0].name === body.name) {
      res.send({ code: 204, msg: "角色名已存在" });
    } else {
      RoleModel.create(body);
      res.send({ code: 201, msg: "添加成功" });
    }
  } else {
    RoleModel.create(body);
    res.send({ code: 201, msg: "添加成功" });
  }
});

//职位表添加
router.post("/positionAdd", async (req, res) => {
  let body = req.body;
  let result = await PositionModel.find({ role: body.role });
  if (result.length > 0) {
    if (result[0].name === body.name) {
      res.send({ code: 204, msg: "职位名已存在" });
    } else {
      PositionModel.create(body);
      res.send({ code: 201, msg: "添加成功" });
    }
  } else {
    PositionModel.create(body);
    res.send({ code: 201, msg: "添加成功" });
  }
});

//权限表添加
router.post("/permissionAdd", async (req, res) => {
  let body = req.body;
  let result = await PermissionModel.find({ position: body.position });
  if (result.length > 0) {
    if (result[0].name === body.name) {
      res.send({ code: 204, msg: "权限名已存在" });
    } else {
      PermissionModel.create(body);
      res.send({ code: 201, msg: "添加成功" });
    }
  } else {
    PermissionModel.create(body);
    res.send({ code: 201, msg: "添加成功" });
  }
});
module.exports = router;
